<template>
  <div class="purchase-orders">
    <!-- 顶部表单区域 -->
    <el-form :model="form" layout="inline" class="top-form">
      <!-- 供应商 -->
      <el-form-item label="供应商">
        <el-select
          v-model="form.supplier"
          placeholder="请选择供应商"
          style="width: 160px"
        >
          <el-option label="示例供应商" value="supplier1"></el-option>
        </el-select>
      </el-form-item>

      <!-- 业务员 -->
      <el-form-item label="业务员">
        <el-select
          v-model="form.salesman"
          placeholder="(空)"
          style="width: 160px"
        >
          <el-option label="示例业务员" value="salesman1"></el-option>
        </el-select>
      </el-form-item>

      <!-- 单据日期 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="form.documentDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择日期"
          style="width: 160px"
        />
      </el-form-item>

      <!-- 交货日期 -->
      <el-form-item label="交货日期">
        <el-date-picker
          v-model="form.deliveryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择日期"
          style="width: 160px"
        />
      </el-form-item>

      <!-- 业务类型 -->
      <el-form-item label="业务类型">
        <el-radio-group
          v-model="form.businessType"
          style="display: flex; align-items: center; gap: 8px"
        >
          <el-radio label="purchase">购货</el-radio>
          <el-radio label="return">退货</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 供应商发货地址 -->
      <el-form-item label="供应商发货地址">
        <el-input
          v-model="form.shippingAddress"
          placeholder="请输入地址"
          style="width: 200px"
        />
      </el-form-item>

      <!-- 上传附件 -->
      <el-form-item>
        <el-button type="text" @click="handleUpload">上传附件</el-button>
      </el-form-item>

      <!-- 单据编号 -->
      <el-form-item>
        <span class="doc-number" style="vertical-align: middle"
          >单据编号: GHDD20250623001</span
        >
      </el-form-item>
    </el-form>

    <!-- 商品表格区域 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        show-summary
        :summary-method="calculateSummary"
      >
        <el-table-column type="selection" width="50" />

        <!-- 商品列：表头集成扫描模式开关，单元格显示名称+图片 -->
        <el-table-column label="商品" width="320">
          <!-- 表头模板：文字 + 扫描模式开关 -->
          <template #label>
            <div class="header-switch">
              <span>商品</span>
              <el-switch
                v-model="columnScanMode"
                active-text="扫描枪"
                inactive-text="手动"
                style="margin-left: 8px"
              />
            </div>
          </template>
          <!-- 单元格模板：名称输入框（手动模式下显示） + 图片 -->
          <template #default="scope">
            <div class="product-cell">
              <el-input
                v-if="!columnScanMode"
                v-model="scope.row.productName"
                placeholder="输入商品名称"
                size="mini"
                style="width: 120px; margin-right: 8px"
              />
              <div class="image-wrapper">
                <el-image
                  v-if="scope.row.image"
                  :src="scope.row.image"
                  style="width: 40px; height: 40px"
                  fit="cover"
                />
                <span v-else class="no-img">无图</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 其他列：移除输入框，改为静态显示 -->
        <el-table-column label="品牌" prop="brand" width="120" />
        <el-table-column label="商品备注" prop="remark" width="150" />
        <el-table-column label="属性" prop="attribute" width="100" />
        <el-table-column label="单位" prop="unit" width="100" />
        <el-table-column label="仓库" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.warehouse" placeholder="选择仓库">
              <el-option label="主仓库" value="warehouse1"></el-option>
              <el-option label="副仓库" value="warehouse2"></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="可用库存" prop="availableStock" width="100" />
        <el-table-column label="数量" prop="quantity" width="100" />
        <el-table-column label="整件散包" prop="wholePackage" width="100" />

        <!-- 价格&折扣相关列（均为静态显示） -->
        <el-table-column label="含税单价" prop="taxPrice" width="120" />
        <el-table-column
          label="折后含税单价"
          prop="discountedTaxPrice"
          width="120"
        />
        <el-table-column label="折扣(折)" prop="discount" width="100" />
        <el-table-column label="折扣额" prop="discountAmount" width="100" />
        <el-table-column label="折后单价" prop="discountedPrice" width="100" />
        <el-table-column label="基本数量" prop="baseQuantity" width="100" />
        <el-table-column label="基本单位" prop="baseUnit" width="100" />
        <el-table-column label="赠品" prop="gift" width="80" />
        <el-table-column label="折扣率(%)" prop="discountRate" width="100" />
        <el-table-column label="购货单价" prop="purchasePrice" width="100" />
        <el-table-column label="金额" prop="amount" width="100" />
        <el-table-column label="价税合计" prop="totalAmount" width="120" />
        <el-table-column label="税额" prop="taxAmount" width="100" />
        <el-table-column label="税率(%)" prop="taxRate" width="100" />
        <el-table-column
          label="关联销货订单号"
          prop="relatedSalesOrder"
          width="150"
        />
        <el-table-column
          label="未入库数量"
          prop="unstoredQuantity"
          width="100"
        />
      </el-table>
    </div>

    <!-- 底部信息区域（保留原逻辑） -->
    <el-form :model="form" class="bottom-form">
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="暂无备注信息"
          :rows="2"
          style="width: 220px; resize: none"
        />
      </el-form-item>
      <el-form-item label="优惠率(%)">
        <el-input-number v-model="form.discountRate" style="width: 100px" />
      </el-form-item>
      <el-form-item label="优惠金额">
        <el-input-number v-model="form.discountAmount" style="width: 100px" />
      </el-form-item>
      <el-form-item label="优惠后金额">
        <span
          class="discount-total"
          style="line-height: 32px; vertical-align: top"
        >
          {{ form.discountedAmount }}
        </span>
      </el-form-item>
      <el-form-item label="交货方式">
        <el-select
          v-model="form.deliveryMethod"
          placeholder="(空)"
          style="width: 120px"
        >
          <el-option label="物流配送" value="logistics"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div class="action-buttons">
      <el-button type="primary" @click="handleSaveAndAdd">保存并新增</el-button>
      <el-button type="success" @click="handleSave">保存</el-button>
      <el-button type="info" @click="handleBatchImport">批量导入</el-button>
      <el-button type="warning" @click="handleApprove">审核</el-button>
      <el-button type="text" @click="viewHistory">历史单据</el-button>
      <el-button type="text" @click="viewOperationLog">操作日志</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PurchaseOrders",
  data() {
    return {
      form: {
        supplier: "",
        salesman: "",
        documentDate: "2025-06-23",
        deliveryDate: "2025-06-23",
        businessType: "purchase",
        shippingAddress: "",
        remark: "",
        discountRate: 0,
        discountAmount: 0,
        discountedAmount: 0,
        deliveryMethod: "",
      },
      activeTab: "input",
      columnScanMode: false, // 表头扫描模式开关（控制整列输入方式）
      tableData: Array.from({ length: 5 }, () => ({
        productName: "",
        image: "",
        brand: "",
        remark: "",
        attribute: "",
        unit: "",
        warehouse: "",
        availableStock: 0,
        quantity: 0,
        wholePackage: "",
        taxPrice: 0,
        discountedTaxPrice: 0,
        discount: 10,
        discountAmount: 0,
        discountedPrice: 0,
        baseQuantity: 0,
        baseUnit: "",
        gift: false,
        discountRate: 0,
        purchasePrice: 0,
        amount: 0,
        totalAmount: 0,
        taxAmount: 0,
        taxRate: 0,
        relatedSalesOrder: "",
        unstoredQuantity: 0,
      })),
      warehouseOptions: [
        { label: "主仓库", value: "warehouse1" },
        { label: "副仓库", value: "warehouse2" },
      ],
    };
  },
  computed: {
    discountedAmount() {
      const totalAmount = this.tableData.reduce(
        (acc, item) => acc + (item.totalAmount || 0),
        0
      );
      return totalAmount - this.form.discountAmount;
    },
  },
  watch: {
    // 保留原计算逻辑（若需动态计算，可根据 columnScanMode 扩展）
    "tableData.*.discountRate": function () {
      this.calculateDiscounts();
    },
    "tableData.*.discount": function () {
      this.calculateDiscounts();
    },
    "tableData.*.taxPrice": function () {
      this.calculateDiscounts();
      this.calculateAmounts();
    },
    "tableData.*.taxRate": function () {
      this.calculateAmounts();
    },
  },
  methods: {
    calculateDiscounts() {
      this.tableData.forEach((item) => {
        if (item.discountRate > 0) {
          item.discountedPrice = item.taxPrice * (1 - item.discountRate / 100);
          item.discountAmount = (item.taxPrice * item.discountRate) / 100;
          item.discount = (1 - item.discountRate / 100) * 10;
        } else if (item.discount > 0) {
          item.discountedPrice = item.taxPrice * (item.discount / 10);
          item.discountAmount = item.taxPrice * (1 - item.discount / 10);
          item.discountRate = (1 - item.discount / 10) * 100;
        } else {
          item.discountedPrice = item.taxPrice;
          item.discountAmount = 0;
          item.discount = 10;
          item.discountRate = 0;
        }
        item.discountedTaxPrice = item.discountedPrice;
      });
    },
    calculateAmounts() {
      this.tableData.forEach((item) => {
        item.amount = item.discountedPrice * item.quantity;
        item.taxAmount = item.amount * (item.taxRate / 100);
        item.totalAmount = item.amount + item.taxAmount;
        item.unstoredQuantity = item.quantity;
      });
    },
    handleUpload() {
      console.log("触发附件上传逻辑");
    },
    calculateSummary({ columns, data }) {
      const sums = [];
      columns.forEach((col, index) => {
        if (index === 0) {
          sums[index] = "合计:";
          return;
        }
        const prop = col.prop;
        if (prop === "quantity") {
          const total = data.reduce((acc, cur) => acc + (cur.quantity || 0), 0);
          sums[index] = total;
        } else if (prop === "totalAmount") {
          const total = data.reduce(
            (acc, cur) => acc + (cur.totalAmount || 0),
            0
          );
          sums[index] = total;
        } else if (prop === "amount") {
          const total = data.reduce((acc, cur) => acc + (cur.amount || 0), 0);
          sums[index] = total;
        } else if (prop === "taxAmount") {
          const total = data.reduce(
            (acc, cur) => acc + (cur.taxAmount || 0),
            0
          );
          sums[index] = total;
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    handleSaveAndAdd() {
      console.log("保存并新增数据:", this.tableData);
      this.$message.success("保存成功");
      this.tableData = [];
    },
    handleSave() {
      console.log("保存数据:", this.tableData);
      this.$message.success("保存成功");
    },
    handleBatchImport() {
      console.log("触发批量导入功能");
    },
    handleApprove() {
      console.log("触发审核流程");
      this.$message({
        type: "warning",
        message: "确定要审核此订单吗？",
      });
    },
    viewHistory() {
      console.log("查看历史单据");
    },
    viewOperationLog() {
      console.log("查看操作日志");
    },
  },
  mounted() {
    this.calculateDiscounts();
    this.calculateAmounts();
  },
};
</script>

<style scoped>
.purchase-orders {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 200px);
}

.top-form {
  margin-bottom: 15px;
  align-items: center;
}

.doc-number {
  line-height: 32px;
  color: #666;
}

.tab-switch {
  margin-bottom: 10px;
}

.el-table {
  margin-bottom: 15px;
}

.no-img {
  display: inline-block;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  background: #f5f7fa;
  color: #999;
  border-radius: 4px;
}

.bottom-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.bottom-form {
  flex: 1;
  margin-bottom: 10px;
}

.discount-total {
  line-height: 32px;
  color: #333;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.top-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 12px;
}

.el-form-item__label {
  min-width: 70px;
  text-align: right;
}

.bottom-form {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex-wrap: wrap;
}

.bottom-form .el-form-item {
  margin-bottom: 0;
}

.table-container {
  overflow-x: auto;
  margin-top: 10px;
  scrollbar-width: thin;
}

/* 表头开关样式 */
.header-switch {
  display: flex;
  align-items: center;
}

/* 商品单元格布局 */
.product-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.image-wrapper {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.no-img {
  font-size: 12px;
  color: #999;
}

.el-table th {
  text-align: center;
}
</style>